package cn.crc.pjblog.componentsdata;


import java.util.List;


import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.ioc.services.PropertyAccess;
/**
 * 修改依赖(commons-beanutils)的包为T内建的PropertyAccess服务
 * @author doublel
 * */
public class GenericValueEncoder<T> implements ValueEncoder<T> {

	private final String labelField;

    private List<T> list;
    private final PropertyAccess adapter;
    
    
    public GenericValueEncoder(List<T> list, String labelField,PropertyAccess adapter) {
            this.list = list;
            this.labelField = labelField;
            this.adapter = adapter;
    }

    public String toClient(T obj) {
            try {
                    if (labelField == null) {
                            return obj + "";
                    } else {
                            return adapter.get(obj, labelField)+"";
                    }
            } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            
            }
            return null;
    }

    public T toValue(String string) {
            try {
                    for (T obj : list) {
                            if (labelField == null) {
                                    if ((obj + "").equals(string)) {
                                            return obj;
                                    }
                            } else {
                                    if (adapter.get(obj, labelField).equals(string)) {
                                            return obj;
                                    }
                            }
                    }
            } catch (Exception e) {
                    // TODO Auto-generated catch block
                  
            }
            return null;
    }



}
